#!/usr/bin/env python
# -*- coding:utf-8 _*-

from __future__ import print_function

import os
import sys
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import seaborn as sns

analyPath = os.getcwd()
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = 10.5


class Train_CV_SGBRT(object):

    def __init__(self):
        self.data_path = analyPath + "/data"

    def analy(self):

        data = pd.read_csv(os.path.join(self.data_path, str(self.algorithm_name) + ".csv"))
        importance = pd.read_csv(os.path.join(analyPath + '/result/importance', str(self.algorithm_name)), sep=',')
        importance = importance[['Linear_iso']].values
        configNum = data.shape[1] - 1
        events_name = data.columns
        data = pd.DataFrame(data.values)

        interactions = np.zeros((configNum, configNum), dtype=float)
        Linear = LinearRegression()
        for i in range(configNum):
            for j in range(i):
                X = data[[i, j]]
                X.insert(X.shape[1], 'xy', data[i].values * data[j].values)
                Linear.fit(X, data[configNum])
                interactions[i][j] = Linear.coef_[2]
                interactions[j][i] = Linear.coef_[2]

        interactions = pd.DataFrame(interactions)
        interactions.index = events_name[0:configNum]
        interactions.columns = events_name[0:configNum]
        interactions.to_csv(analyPath + '/result/xy-interaction/' + str(self.algorithm_name))

        plt.figure(figsize=(configNum * 0.2 + 2, configNum * 0.2), frameon=False)
        sns.heatmap(data=interactions, annot=False, xticklabels=events_name[0:-1], yticklabels=events_name[0:-1], annot_kws={'size': 10.5, 'weight': 'normal', 'color': '#66ccff'}, fmt='.0f')
        plt.tight_layout()
        plt.savefig(analyPath + '/result/xy-interaction/' + str(self.algorithm_name) + '.pdf')

    def build(self, item):
        self.algorithm_name = item.replace(".csv", "")
        self.analy()

    def build_loop(self):
        path_list = os.listdir(self.data_path)
        for i in path_list:
            if i != ".gitignore":
                self.algorithm_name = i.replace(".csv", "")
                print(self.algorithm_name)
                self.analy()


if __name__ == '__main__':
    train_cv_sgbrt = Train_CV_SGBRT()
    train_cv_sgbrt.__init__()
    if len(sys.argv) > 1 and sys.argv[1] != 'all':
        train_cv_sgbrt.build(sys.argv[1])
    else:
        train_cv_sgbrt.build_loop()
